package com.example.softwareconfigurationcoursedesign.Admin;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

@WebServlet(value = "/DeleteProductServlet")
public class DeleteProductServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // 获取产品ID
    int productId = Integer.parseInt(request.getParameter("productId"));  // 从请求中获取产品ID参数

    // 连接数据库
    String jdbcUrl = "jdbc:mysql://localhost:3306/course_design";
    String dbUser = "root";
    String dbPassword = "123456";

    try (Connection connection = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword)) {
        // 执行删除操作
        String sql = "DELETE FROM products WHERE id = ?";  // 构建删除SQL语句
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, productId);  // 设置SQL语句中的参数
            int rowsDeleted = statement.executeUpdate();  // 执行删除操作并获取影响的行数
            if (rowsDeleted > 0) {
                response.sendRedirect("Admin_Product.jsp");  // 删除成功，重定向到Admin_Product.jsp页面
            } else {
                response.getWriter().write("error");  // 删除失败，向客户端返回错误信息
            }
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);  // 打印异常信息
        response.getWriter().write("error");  // 向客户端返回错误信息
    }
}
}